package com.dooioo.pns.business.service;

import com.dooioo.pns.base.service.BaseService;
import com.dooioo.pns.core.config.Constants;
import com.dooioo.pns.entity.model.AppInfo;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * PackageName:com.dooioo.pns.business.service
 * Author: Jerry.hu
 * Create: Jerry.hu (2015-05-07 下午1:18)
 * Description:客户端 app 信息业务
 */
@Service
public class AppInfoService extends BaseService<AppInfo> {
	private Map<Integer,Map<String,String>> appHeaderMap = new HashMap<>();

	/**
	 * 插入app 信息，并返回主键id
	 * @param appInfo
	 * @return
	 */
	public int insertAndReturnId(AppInfo appInfo){
		if(super.insertAndReturnId(sqlId("insertAndReturnId"),appInfo) >0){
			return appInfo.getId();
		}
		return 0;
	}

	/**
	 * 根据appId 获取learnCloud 请求的头部参数
	 * @param appId appInfo 主键id
	 * @return map
	 */
	public Map<String,String> getHeaderMap(int appId){
		if(appHeaderMap.containsKey(appId)){
			return appHeaderMap.get(appId);
		}else{
			AppInfo appInfo = super.selectOne(sqlId("queryBeanById"),appId);
			if(appInfo != null){
				Map<String,String> map = new HashMap<>();
				map.put(Constants.X_AVOSCloud_Application_Id,appInfo.getAppId());
				map.put(Constants.X_AVOSCloud_Application_Key,appInfo.getAppKey());
				map.put(Constants.CONTENT_TYPE_KEY,Constants.CONTENT_TYPE);
				appHeaderMap.put(appId,map);
				return map;
			}
		}
		return null;
	}

	/**
	 * 验证appId 是否存在
	 * @param appId
	 * @return
	 */
	public boolean isExists(int appId){
		return super.count(sqlId("isExists"),appId) > 0;
	}

	public boolean isExistsApp(String appName) {
		return super.count(sqlId("isExistsApp"),appName) > 0;
	}
}
